import React, { useState } from 'react';
import Cubox from './Cubox';
import styles from './CuboxSlider.module.css';
import colorScheme from './color-scheme';

const CuboxSlider = ({ 
  value = 0, 
  onChange, 
  min = 0, 
  max = 100, 
  step = 1,
  isDisabled = false, 
  color = 'blue', 
  style, 
  showValue = true,
  valueFormatter = (val) => val,
  cornerRadius = 20,
  strokeWidth = 1,
  ...props 
}) => {
  const [isFocused, setIsFocused] = useState(false);

  const [back, fore, text] = isDisabled
    ? ['base01', 'base01', 'base06']  
    : [color, 'base00', 'base06'];

  const QBOXProps = {
    cornerRadius,
    strokeWidth, 
    isOutlined: true,
    backColor: colorScheme[back],
    foreColor: colorScheme[fore],
    style: { width: '100%', ...style }
  };

  const handleChange = (e) => {
    if (!isDisabled && onChange) {
      const newValue = parseFloat(e.target.value);
      onChange(newValue);
    }
  };

  const handleFocus = (e) => {
    setIsFocused(true);
    if (props.onFocus) props.onFocus(e);
  };

  const handleBlur = (e) => {
    setIsFocused(false);
    if (props.onBlur) props.onBlur(e);
  };

  const inputProps = {
    type: 'range',
    min,
    max,
    step,
    value,
    onChange: handleChange,
    onFocus: handleFocus,
    onBlur: handleBlur,
    disabled: isDisabled,
    className: styles.slider,
    style: {
      color: colorScheme[text],
    },
    ...props
  };

  return (
    <div className={styles.container}>
      <Cubox {...QBOXProps}>
        <div className={styles.sliderWrapper}>
          <input {...inputProps} />
          {showValue && (
            <span className={styles.value}>
              {valueFormatter(value)}
            </span>
          )}
        </div>
      </Cubox>
    </div>
  );
};

export default CuboxSlider;
